<template>
  <div class="role-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>角色权限管理</h3>
          <el-button class="add-button" @click="handleAdd">+ 添加权限组</el-button>
        </div>
      </template>

      <el-table :data="roleList" border v-loading="loading">
        <el-table-column prop="id" label="ID号" width="80" align="center" />
        <el-table-column prop="title" label="权限组名称" width="200" />
        <el-table-column prop="desc" label="备注" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-dropdown>
                <el-button size="small">
                  更多
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEdit(scope.row)">编辑</el-dropdown-item>
                    <el-dropdown-item @click="handleDelete(scope.row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑角色抽屉 -->
    <GlobalDrawer
      v-model="drawerVisible"
      :title="drawerTitle"
      size="80%"
      @close="handleDrawerClose"
      @confirm="submitRole"
    >
      <div class="drawer-content-wrapper">
        <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="权限组名称" prop="title">
                <el-input v-model="roleForm.title" placeholder="请输入权限组名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="roleForm.status">
                  <el-radio :label="1">正常</el-radio>
                  <el-radio :label="-1">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="权限配置" v-loading="ruleTreeLoading" class="rule-tree-container">
            <!-- 调试信息：显示按钮权限节点数量 -->
            <div class="debug-info">按钮权限节点数量：{{ countButtonPermissions(ruleTree) }}</div>
            <el-table :data="formattedRuleTree" border class="rule-table">
              <el-table-column label="选择可操作的顶级权限" width="180" align="center">
                <template #default="scope">
                  <div class="permission-node permission-node-root">
                    <div class="permission-node-content">
                      <el-checkbox
                        v-model="scope.row.checked"
                        :label="scope.row.title"
                        :value="scope.row.id"
                        @change="
                          (val: boolean) => handlePermissionChange(val, scope.row, null, null)
                        "
                      ></el-checkbox>
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="选择可操作的子级权限">
                <template #default="scope">
                  <div
                    class="permission-tree-container"
                    v-if="scope.row.children && scope.row.children.length > 0"
                  >
                    <!-- 一级菜单节点 -->
                    <div v-for="child in scope.row.children" :key="child.id">
                      <!-- 一级菜单节点 -->
                      <div
                        v-if="child.menu === 1"
                        class="permission-node permission-node-menu permission-node-level-1"
                      >
                        <div class="permission-node-content">
                          <el-checkbox
                            v-model="child.checked"
                            :label="child.title"
                            :value="child.id"
                            @change="
                              (val: boolean) => handlePermissionChange(val, child, scope.row, null)
                            "
                          ></el-checkbox>
                        </div>

                        <!-- 二级菜单节点 -->
                        <div
                          class="permission-children"
                          v-if="child.children && child.children.length > 0"
                        >
                          <div v-for="subChild in child.children" :key="subChild.id">
                            <!-- 二级菜单节点 -->
                            <div
                              v-if="subChild.menu === 1"
                              class="permission-node permission-node-menu permission-node-level-2"
                            >
                              <div class="permission-node-content">
                                <el-checkbox
                                  v-model="subChild.checked"
                                  :label="subChild.title"
                                  :value="subChild.id"
                                  @change="
                                    (val: boolean) =>
                                      handlePermissionChange(val, subChild, child, scope.row)
                                  "
                                ></el-checkbox>
                              </div>

                              <!-- 二级菜单下的子节点 -->
                              <div v-if="subChild.children && subChild.children.length > 0">
                                <!-- 按钮节点 - 与三级菜单同级显示 -->
                                <div
                                  class="permission-buttons"
                                  v-if="
                                    subChild.children.some(
                                      (child: PermissionNode) => child.menu === 2
                                    )
                                  "
                                >
                                  <template
                                    v-for="subSubChild in subChild.children"
                                    :key="subSubChild.id"
                                  >
                                    <div
                                      v-if="subSubChild.menu === 2"
                                      class="permission-node-button"
                                    >
                                      <el-checkbox
                                        v-model="subSubChild.checked"
                                        :label="subSubChild.title"
                                        :value="subSubChild.id"
                                        @change="
                                          (val: boolean) =>
                                            handlePermissionChange(
                                              val,
                                              subSubChild,
                                              subChild,
                                              child
                                            )
                                        "
                                      >
                                        {{ subSubChild.title }}
                                      </el-checkbox>
                                    </div>
                                  </template>
                                </div>

                                <!-- 三级菜单节点 -->
                                <div v-for="subSubChild in subChild.children" :key="subSubChild.id">
                                  <div
                                    v-if="subSubChild.menu === 1"
                                    class="permission-node permission-node-menu permission-node-level-3"
                                  >
                                    <div class="permission-node-content">
                                      <el-checkbox
                                        v-model="subSubChild.checked"
                                        :label="subSubChild.title"
                                        :value="subSubChild.id"
                                        @change="
                                          (val: boolean) =>
                                            handlePermissionChange(
                                              val,
                                              subSubChild,
                                              subChild,
                                              child
                                            )
                                        "
                                      >
                                        {{ subSubChild.title }}
                                      </el-checkbox>
                                    </div>

                                    <!-- 按钮节点 - 与三级菜单关联，平铺显示 -->
                                    <div
                                      class="permission-buttons"
                                      v-if="
                                        subSubChild.children &&
                                        subSubChild.children.some(
                                          (child: PermissionNode) => child.menu === 2
                                        )
                                      "
                                    >
                                      <template
                                        v-for="btnNode in subSubChild.children || []"
                                        :key="btnNode.id"
                                      >
                                        <div
                                          v-if="btnNode.menu === 2"
                                          class="permission-node-button"
                                        >
                                          <el-checkbox
                                            v-model="btnNode.checked"
                                            :label="btnNode.title"
                                            :value="btnNode.id"
                                            @change="
                                              (val: boolean) =>
                                                handlePermissionChange(
                                                  val,
                                                  btnNode,
                                                  subSubChild,
                                                  subChild
                                                )
                                            "
                                          >
                                            {{ btnNode.title }}
                                          </el-checkbox>
                                        </div>
                                      </template>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <!-- 一级菜单关联的按钮节点 -->
                      <div
                        class="permission-buttons"
                        v-if="
                          child.children &&
                          child.children.some((child: PermissionNode) => child.menu === 2)
                        "
                      >
                        <template v-for="btnNode in child.children" :key="btnNode.id">
                          <div v-if="btnNode.menu === 2" class="permission-node-button">
                            <el-checkbox
                              v-model="btnNode.checked"
                              :label="btnNode.title"
                              :value="btnNode.id"
                              @change="
                                (val: boolean) =>
                                  handlePermissionChange(val, btnNode, child, scope.row)
                              "
                            >
                              {{ btnNode.title }}
                            </el-checkbox>
                          </div>
                        </template>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="布局配置">
            <div class="layout-options">
              <el-checkbox
                v-for="item in layoutOptions"
                :key="item.id"
                v-model="item.checked"
                :label="item.title"
                :value="item.id"
                @change="(val: boolean) => handleLayoutCheckChange(val, item)"
              ></el-checkbox>
            </div>
          </el-form-item>

          <el-form-item label="备注内容">
            <el-input v-model="roleForm.desc" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
      </div>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { GlobalDrawer } from '@/components/common'
  import {
    getRoleList as getRoleListApi,
    saveRole as saveRoleApi,
    deleteRole as deleteRoleApi,
    getPermissionTree,
    getRoleDetail,
  } from '@/api/home/role'
  import { ArrowDown } from '@element-plus/icons-vue'

  // 权限节点类型定义
  interface PermissionNode {
    id: number
    title: string
    menu: 0 | 1 | 2
    checked: boolean
    children?: PermissionNode[]
  }

  // 数据相关
  const roleList = ref<any[]>([])
  const loading = ref(false)

  // 抽屉相关
  const drawerVisible = ref(false)
  const drawerTitle = ref('')
  const isEdit = ref(false)
  const ruleTreeLoading = ref(false)

  // 表单数据
  const roleForm = reactive({
    id: 0,
    title: '',
    status: 1,
    desc: '',
    rule: [] as number[],
    layout: [] as number[],
  })

  // 表单验证规则
  const roleRules = {
    title: [{ required: true, message: '请输入权限组名称', trigger: 'blur' }],
  }

  // 树形控件相关
  const ruleTree = ref<PermissionNode[]>([])
  const layoutTree = ref<PermissionNode[]>([])
  const layoutOptions = ref([
    { id: 1, title: '首页', checked: false },
    { id: 2, title: '用户管理', checked: false },
    { id: 3, title: '系统设置', checked: false },
  ])

  // 格式化后的权限树数据
  const formattedRuleTree = computed(() => {
    return ruleTree.value
  })

  // 表单引用
  const roleFormRef = ref()

  // 获取角色列表
  const getRoleList = async () => {
    try {
      loading.value = true
      const response = await getRoleListApi()

      // 确保数据格式正确
      if (Array.isArray(response.data)) {
        roleList.value = response.data
      } else if (response.data && Array.isArray(response.data.list)) {
        // 兼容可能的数据结构，如果数据在list字段中
        roleList.value = response.data.list
      } else {
        roleList.value = []
      }
    } catch (error) {
      console.error('Failed to fetch role list:', error)
      ElMessage.error('获取角色列表失败: ' + ((error as any).message || '未知错误'))
      roleList.value = []
    } finally {
      loading.value = false
    }
  }

  // 处理添加
  const handleAdd = () => {
    isEdit.value = false
    drawerTitle.value = '添加角色'
    roleForm.id = 0
    roleForm.title = ''
    roleForm.status = 1
    roleForm.desc = ''
    roleForm.rule = []
    roleForm.layout = []
    drawerVisible.value = true

    // 获取树形数据
    getRuleTree()
    getLayoutTree()
  }

  // 处理编辑
  const handleEdit = async (row: any) => {
    try {
      // 先显示加载状态
      ruleTreeLoading.value = true

      // 调试信息：查看传入的row数据
      console.log('编辑角色传入的row数据:', row)
      console.log('row是否包含rule_ids:', 'rule_ids' in row)
      console.log('row是否包含rules_array:', 'rules_array' in row)

      // 优先使用角色列表中的数据
      let roleData = row
      let useRowData = true

      // 检查row数据是否包含完整的权限信息
      if (!row.rule_ids || !Array.isArray(row.rule_ids) || row.rule_ids.length === 0) {
        // 如果角色列表数据不完整，调用getRoleDetail获取详细信息
        console.log('角色列表数据不完整，调用getRoleDetail获取详细信息')
        try {
          const roleDetailResponse = await getRoleDetail(row.id)

          if (roleDetailResponse.code === 0) {
            roleData = roleDetailResponse.data
            useRowData = false

            // 调试信息：查看角色详情数据
            console.log('编辑角色详情数据:', roleData)
          } else {
            ElMessage.error('获取角色详情失败: ' + roleDetailResponse.msg)
            return
          }
        } catch (error) {
          console.error('获取角色详情API调用失败:', error)
          ElMessage.error('获取角色详情失败')
          return
        }
      }

      // 调试信息：查看角色数据
      console.log('角色标题:', roleData.title)
      console.log('原始rule_ids:', roleData.rule_ids)
      console.log('使用来源:', useRowData ? '角色列表数据' : 'getRoleDetail API')

      isEdit.value = true
      drawerTitle.value = '编辑角色'
      roleForm.id = roleData.id
      roleForm.title = roleData.title
      roleForm.status = roleData.status
      roleForm.desc = roleData.desc

      // 确保rule_ids是数组类型，并转换为数字数组
      if (Array.isArray(roleData.rule_ids)) {
        roleForm.rule = roleData.rule_ids.map((id: any) => Number(id))
      } else if (Array.isArray(roleData.rules_array)) {
        // 兼容可能的rules_array字段
        roleForm.rule = roleData.rules_array.map((id: any) => Number(id))
      } else {
        roleForm.rule = []
      }

      roleForm.layout = Array.isArray(roleData.layout_ids)
        ? roleData.layout_ids.map((id: any) => Number(id))
        : []

      // 调试信息：查看转换后的权限列表
      console.log('转换后的权限列表:', roleForm.rule)

      drawerVisible.value = true

      // 获取树形数据
      await getRuleTree()
      getLayoutTree()
    } catch (error) {
      console.error('获取角色详情失败:', error)
      ElMessage.error('获取角色详情失败: ' + ((error as any).message || '未知错误'))
    } finally {
      ruleTreeLoading.value = false
    }
  }

  // 获取权限树
  const getRuleTree = async () => {
    try {
      ruleTreeLoading.value = true
      const response = await getPermissionTree()

      if (response.code === 0 && Array.isArray(response.data)) {
        // 深拷贝数据，避免直接修改源数据
        const treeData = JSON.parse(JSON.stringify(response.data))

        // 调试信息：查看角色和权限数据
        console.log('权限树原始数据:', JSON.stringify(response.data, null, 2))
        console.log('当前角色ID:', roleForm.id)
        console.log('当前角色权限列表:', roleForm.rule)
        console.log('权限列表长度:', roleForm.rule.length)

        // 为每个节点添加checked属性，并根据当前角色的权限设置选中状态
        setCheckedState(treeData)

        ruleTree.value = treeData

        // 调试信息：查看处理后的权限树数据
        console.log('处理后的权限树数据:', JSON.stringify(treeData, null, 2))

        // 详细日志：统计各级权限节点数量
        const countMenuNodes = (nodes: PermissionNode[], level: number) => {
          let menuCount = 0
          let buttonCount = 0

          nodes.forEach(node => {
            if (node.menu === 1) {
              menuCount++
              if (node.children && node.children.length > 0) {
                const childCounts = countMenuNodes(node.children, level + 1)
                menuCount += childCounts.menuCount
                buttonCount += childCounts.buttonCount
              }
            } else if (node.menu === 2) {
              buttonCount++
            }
          })

          return { menuCount, buttonCount }
        }

        const counts = countMenuNodes(treeData, 1)
      } else {
        console.warn('Permission tree data format is incorrect:', response.data)
        ruleTree.value = []
      }
    } catch (error) {
      console.error('Failed to fetch permission tree:', error)
      ElMessage.error('获取权限树失败: ' + ((error as any).message || '未知错误'))
      ruleTree.value = []
    } finally {
      ruleTreeLoading.value = false
    }
  }

  // 获取布局树
  const getLayoutTree = async () => {
    // 这里应该调用获取布局树的API
    // 示例数据
    layoutTree.value = []
  }

  // 设置权限节点的选中状态
  const setCheckedState = (nodes: PermissionNode[]) => {
    nodes.forEach(node => {
      // 确保ID类型匹配，转换为字符串进行比较
      const nodeId = String(node.id)
      const ruleIds = roleForm.rule.map(id => String(id))

      // 检查当前节点是否在角色权限列表中
      node.checked = ruleIds.includes(nodeId)

      // 调试信息：查看节点的勾选状态
      console.log(
        `节点 ${node.title} (ID: ${node.id}, 类型: ${typeof node.id}) - ` +
          `权限列表包含: ${ruleIds.includes(nodeId)}, 勾选状态: ${node.checked}`
      )

      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        setCheckedState(node.children)

        // 如果有子节点被选中，当前节点也应该被选中
        if (!node.checked) {
          node.checked = node.children.some((child: PermissionNode) => child.checked)
          console.log(`更新节点 ${node.title} 勾选状态为: ${node.checked} (因为有子节点被选中)`)
        }
      }
    })
  }

  // 统计按钮权限节点数量
  const countButtonPermissions = (nodes: PermissionNode[]): number => {
    let count = 0
    nodes.forEach(node => {
      // 统计当前节点如果是按钮权限
      if (node.menu === 2) {
        count++
      }
      // 递归统计子节点
      if (node.children && node.children.length > 0) {
        count += countButtonPermissions(node.children)
      }
    })
    return count
  }

  // 处理权限变更
  const handlePermissionChange = (
    checked: boolean,
    node: PermissionNode,
    parentNode: PermissionNode | null,
    grandparentNode: PermissionNode | null
  ) => {
    // 更新当前节点状态
    node.checked = checked

    // 处理子节点状态 - 如果当前节点被选中，所有子节点也应该被选中
    if (node.children && node.children.length > 0) {
      updateChildNodes(node.children, checked)
    }

    // 处理父节点状态 - 如果当前节点被选中，父节点也应该被选中
    if (parentNode) {
      updateParentNode(parentNode)
    }

    // 处理祖父节点状态
    if (grandparentNode) {
      updateParentNode(grandparentNode)
    }

    // 更新角色表单中的权限列表
    updateRolePermissions()
  }

  // 更新子节点状态
  const updateChildNodes = (nodes: PermissionNode[], checked: boolean) => {
    nodes.forEach(node => {
      node.checked = checked
      if (node.children && node.children.length > 0) {
        updateChildNodes(node.children, checked)
      }
    })
  }

  // 更新父节点状态
  const updateParentNode = (node: PermissionNode) => {
    // 检查是否所有子节点都被选中
    const allChecked =
      node.children &&
      node.children.length > 0 &&
      node.children.every((child: PermissionNode) => child.checked)

    // 检查是否有任何子节点被选中
    const anyChecked =
      node.children &&
      node.children.length > 0 &&
      node.children.some((child: PermissionNode) => child.checked)

    // 更新父节点状态
    if (allChecked || anyChecked) {
      node.checked = true
    } else {
      node.checked = false
    }
  }

  // 更新角色表单中的权限列表
  const updateRolePermissions = () => {
    const permissions: number[] = []

    // 收集所有被选中的权限节点ID
    collectPermissions(ruleTree.value, permissions)

    // 更新角色表单
    roleForm.rule = permissions
  }

  // 收集所有被选中的权限节点ID
  const collectPermissions = (nodes: PermissionNode[], permissions: number[]) => {
    nodes.forEach(node => {
      if (node.checked) {
        permissions.push(node.id)
      }

      if (node.children && node.children.length > 0) {
        collectPermissions(node.children, permissions)
      }
    })
  }

  // 查看角色详情
  const handleView = async (row: any) => {
    try {
      // 先显示加载状态
      ruleTreeLoading.value = true

      // 调试信息：查看传入的row数据
      console.log('查看角色传入的row数据:', row)
      console.log('row是否包含rule_ids:', 'rule_ids' in row)
      console.log('row是否包含rules_array:', 'rules_array' in row)

      // 优先使用角色列表中的数据
      let roleData = row
      let useRowData = true

      // 检查row数据是否包含完整的权限信息
      if (!row.rule_ids || !Array.isArray(row.rule_ids) || row.rule_ids.length === 0) {
        // 如果角色列表数据不完整，调用getRoleDetail获取详细信息
        console.log('角色列表数据不完整，调用getRoleDetail获取详细信息')
        try {
          const roleDetailResponse = await getRoleDetail(row.id)

          if (roleDetailResponse.code === 0) {
            roleData = roleDetailResponse.data
            useRowData = false

            // 调试信息：查看角色详情数据
            console.log('查看角色详情数据:', roleData)
          } else {
            ElMessage.error('获取角色详情失败: ' + roleDetailResponse.msg)
            return
          }
        } catch (error) {
          console.error('获取角色详情API调用失败:', error)
          ElMessage.error('获取角色详情失败')
          return
        }
      }

      // 调试信息：查看角色数据
      console.log('角色标题:', roleData.title)
      console.log('原始rule_ids:', roleData.rule_ids)
      console.log('使用来源:', useRowData ? '角色列表数据' : 'getRoleDetail API')

      roleForm.id = roleData.id
      roleForm.title = roleData.title
      roleForm.status = roleData.status
      roleForm.desc = roleData.desc

      // 处理layout_ids，兼容字符串和数组类型
      if (Array.isArray(roleData.layout_ids)) {
        roleForm.layout = roleData.layout_ids.map((id: any) => Number(id))
      } else if (typeof roleData.layout_ids === 'string') {
        try {
          roleForm.layout = JSON.parse(roleData.layout_ids).map((id: any) => Number(id))
        } catch (e) {
          roleForm.layout = []
        }
      } else {
        roleForm.layout = []
      }

      // 确保rule_ids是数组类型，并转换为数字数组
      if (Array.isArray(roleData.rule_ids)) {
        roleForm.rule = roleData.rule_ids.map((id: any) => Number(id))
      } else if (Array.isArray(roleData.rules_array)) {
        // 兼容可能的rules_array字段
        roleForm.rule = roleData.rules_array.map((id: any) => Number(id))
      } else {
        roleForm.rule = []
      }

      // 调试信息：查看转换后的权限列表
      console.log('转换后的权限列表:', roleForm.rule)

      isEdit.value = false
      drawerTitle.value = '查看角色'
      drawerVisible.value = true

      // 获取权限树和布局树
      await getRuleTree()
      getLayoutTree()
    } catch (error) {
      console.error('获取角色详情失败:', error)
      ElMessage.error('获取角色详情失败: ' + ((error as any).message || '未知错误'))
    } finally {
      ruleTreeLoading.value = false
    }
  }

  // 删除角色
  const handleDelete = async (row: any) => {
    ElMessageBox.confirm(`确认删除角色【${row.title}】吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const response = await deleteRoleApi(row.id)

          if (response.code === 0) {
            ElMessage.success('删除成功')
            await getRoleList()
          } else {
            ElMessage.error(response.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 提交角色
  const submitRole = async () => {
    if (drawerTitle.value === '查看角色') {
      // 查看模式下，点击确认按钮仅关闭抽屉
      drawerVisible.value = false
      return
    }

    if (!roleFormRef.value) return

    try {
      await roleFormRef.value.validate()

      const params = {
        id: roleForm.id,
        title: roleForm.title,
        status: roleForm.status,
        desc: roleForm.desc,
        rules: roleForm.rule,
        layouts: roleForm.layout,
      }

      const response = await saveRoleApi(params)

      if (response.code === 0) {
        ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
        drawerVisible.value = false
        await getRoleList()
      } else {
        ElMessage.error(response.msg || (isEdit.value ? '编辑失败' : '添加失败'))
      }
    } catch (error) {
      ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
    }
  }

  // 关闭抽屉
  const handleDrawerClose = () => {
    roleFormRef.value?.resetFields()
  }

  // 处理布局选择变化
  const handleLayoutCheckChange = (checked: boolean, data: any) => {
    // 处理布局选择变化
    console.log('布局选择变化:', checked, data)
  }

  // 初始化
  onMounted(() => {
    getRoleList()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  /* 按钮样式规范 */
  .add-button {
    background-color: #67c23a !important;
    border-color: #67c23a !important;
    color: #ffffff !important;
  }

  .red {
    color: #f56c6c;
  }

  .rule-table {
    width: 100%;
  }

  /* 权限树容器 */
  .permission-tree-container {
    padding-left: 10px;
  }

  /* 权限节点基础样式 */
  .permission-node {
    margin-bottom: 8px;
    transition: all 0.3s ease;
  }

  .permission-node-content {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    border-radius: 4px;
    transition: all 0.3s ease;
  }

  .permission-node-content:hover {
    background-color: #f5f7fa;
  }

  /* 菜单节点样式 - 有子节点的为菜单 */
  .permission-node-menu {
    margin-bottom: 8px;
    display: block;
  }

  /* 菜单层级样式 - 用缩进和不同颜色区分 */
  .permission-node-menu.permission-node-level-1 .permission-node-content {
    font-weight: 600;
    font-size: 14px;
    border-left: 4px solid #409eff; /* 一级菜单蓝色 */
    background-color: #ecf5ff;
  }

  .permission-node-menu.permission-node-level-2 .permission-node-content {
    font-weight: 500;
    font-size: 13px;
    border-left: 4px solid #67c23a; /* 二级菜单绿色 */
    margin-left: 20px; /* 缩进20px */
    background-color: #f0f9eb;
  }

  .permission-node-menu.permission-node-level-3 .permission-node-content {
    font-size: 12px;
    border-left: 4px solid #e6a23c; /* 三级菜单橙色 */
    margin-left: 40px; /* 缩进40px */
    background-color: #fdf6ec;
  }

  /* 按钮节点样式 - 无子节点的为按钮，统一颜色标识 */
  /* 该样式已在下方优化版本中重新定义 */

  /* 子节点容器 */
  .permission-children {
    margin-top: 4px;
  }

  /* 按钮容器 - 平铺显示 */
  .permission-buttons {
    margin: 8px 0 0 40px;
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: center;
  }

  /* 按钮节点样式 - 简化显示 */
  .permission-node-button {
    display: inline-flex;
    margin: 0;
    font-size: 12px;
  }

  /* 已勾选和未勾选节点的文字颜色区分 */
  .permission-node-content,
  .permission-node-button {
    color: #909399; /* 默认未勾选的浅色文字 */
    transition: color 0.3s ease;
  }

  .permission-node-content:has(.is-checked),
  .permission-node-button:has(.is-checked) {
    color: #303133; /* 已勾选的深色文字 */
  }

  .right-note {
    padding: 0 0 0 10px;
  }

  /* 操作栏样式 */
  .operation-buttons {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .operation-buttons .el-button {
    margin-right: 8px;
  }

  .operation-buttons .el-dropdown {
    margin-left: 0;
    vertical-align: top;
  }

  .note-item {
    padding: 10px 0;
  }

  .sub-note {
    padding: 0 0 3px 22px;
    margin-bottom: 3px;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;
  }

  .sub-note-item {
    margin-right: 10px;
    display: inline-block;
  }

  .sub-sub-note {
    padding: 6px 0 15px 22px;
    margin-bottom: 3px;
    padding-bottom: 10px;
    margin-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  .sub-sub-note-item {
    margin-right: 10px;
    display: inline-block;
  }
</style>
